package com.share.device.emqx.callback;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.share.device.emqx.EmqxClientWrapper;
import com.share.device.emqx.ProtocolConvertUtil;
import com.share.device.emqx.factory.MessageHandlerFactory;
import com.share.device.emqx.handler.MassageHandler;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OnMessageCallback implements MqttCallback {

    @Autowired
    private MessageHandlerFactory messageHandlerFactory;

//    @Autowired
//    private EmqxClientWrapper emqxClientWrapper;


    @Override
    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        System.out.println("连接断开，可以做重连");
       // emqxClientWrapper.connect();
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        log.info("接收消息主题:{}", topic);
        log.info("接收消息Qos:{}", message.getQos());
        log.info("接收消息内容:{}", new String(message.getPayload()));
        
        try {
            // 解析消息内容
            String payload = new String(message.getPayload());
            JSONObject jsonObject = JSONObject.parseObject(payload);
            
            // 获取消息处理器
            MassageHandler handler = messageHandlerFactory.getMassageHandler(topic);
            if (handler != null) {
                handler.handleMessage(jsonObject);
            } else {
                log.warn("未找到对应的消息处理器: topic={}", topic);
            }
        } catch (Exception e) {
            log.error("处理消息失败: topic={}, message={}", topic, new String(message.getPayload()), e);
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }
}
